package com.chai.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.chai.constant.RedisConstant;
import com.chai.dao.SetmealDao;
import com.chai.pojo.Setmeal;
import com.chai.service.SetmealService;
import com.chai.vo.PageResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    SetmealDao setmealDao;

    @Autowired
    JedisPool jedisPool;

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setmealDao.findPage(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void add(Integer[] travelgroupIds, Setmeal setmeal) {
        setmealDao.add(setmeal);


        Integer setmealId = setmeal.getId();

        setSetmealAndTravelGroup(setmealId, travelgroupIds);

        //保存图片名称到数据库时，记录图片名称
        String imgName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,imgName);
    }

    @Override
    public List<Setmeal> findAll() {

        return setmealDao.findAll();
    }

    @Override
    public Setmeal get(Integer id) {

        return setmealDao.get(id);
    }

    @Override
    public Setmeal findById(Integer id) {

        return setmealDao.findById(id);
    }

    private void setSetmealAndTravelGroup(Integer setmealId, Integer[] travelgroupIds) {
        if (travelgroupIds != null && travelgroupIds.length > 0) {
            for (Integer travelgroupId : travelgroupIds) {
                setmealDao.setSetmealAndTravelGroup(setmealId, travelgroupId);
            }

        }
    }

    @Override
    public List<Map<String, Object>> getSetmealReport() {

        return setmealDao.getSetmealReport();
    }
}
